<script lang="ts">
export default {
  name: 'UpdateUser',
};
</script>

<script setup lang="ts">
import type { FormRule, SubmitContext } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

import { getUserInfosById, updateUser } from '@/api/user';
import { GENDER_ENUM, GENDER_MAP, SPORT_LEVEL_ENUM, SPORT_LEVEL_MAP } from '@/constants/user';
import { useTabHook } from '@/utils/tabs';

const FORM_RULES: Record<string, FormRule[]> = {
  userName: [{ required: true, message: '请输入用户名', type: 'error' }],
  tel: [{ required: true, message: '请输入手机号', type: 'error' }],
  sportsLevel: [{ required: true, message: '请输入运动级别', type: 'error' }],
};

const INITIAL_DATA = {
  userName: '',
  password: '',
  tel: '',
  email: '',
  avatar: '',
  gender: GENDER_ENUM.MALE,
  age: 20,
  sportsCategory: '',
  sportsLevel: SPORT_LEVEL_ENUM.BEGINNER,
  nickname: '',
  wechatId: '',
  comment: '',
};

const { handleRemoveCurrentTab } = useTabHook();

const formData = ref({ ...INITIAL_DATA });

const onReset = () => {
  MessagePlugin.warning('取消新建');
  handleRemoveCurrentTab();
};

const route = useRoute();

/** 初始化页面数据 */
const initPageData = async () => {
  const { query } = route;
  if (query?.userId) {
    const userInfos = await getUserInfosById(query.userId as string);
    formData.value = { ...formData.value, ...userInfos, gender: Number(userInfos.gender) };
    await MessagePlugin.success('用户信息查询成功');
  } else {
    await MessagePlugin.warning('userId参数不存在');
  }
};

onMounted(() => {
  initPageData();
});

const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      const res = await updateUser({ ...formData.value, userId: route.query.userId as string });
      if (res) {
        await MessagePlugin.success('更新成功');
        handleRemoveCurrentTab();
      } else {
        await MessagePlugin.error('更新失败');
      }
    } catch (err) {
      await MessagePlugin.error(err?.message || '更新失败');
    }
  }
};
</script>

<template>
  <t-form
    ref="form"
    class="base-form"
    :data="formData"
    :rules="FORM_RULES"
    label-align="right"
    :label-width="100"
    @reset="onReset"
    @submit="onSubmit"
  >
    <div class="form-basic-container">
      <div class="form-basic-item">
        <div class="form-basic-container-title">用户基本信息</div>
        <t-row class="row-gap" :gutter="[32, 24]">
          <t-col :span="6">
            <t-form-item label-align="top" label="姓名" name="userName">
              <t-input v-model="formData.userName" placeholder="请输入姓名" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="密码" name="password">
              <t-input v-model="formData.password" type="password" placeholder="请输入密码" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="邮箱" name="email">
              <t-input v-model="formData.email" placeholder="请输入邮箱" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="手机号" name="tel">
              <t-input v-model="formData.tel" maxlength="11" type="tel" placeholder="请输入手机号" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="头像" name="avatar">
              <t-input v-model="formData.avatar" placeholder="请输入头像URL" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="性别" name="gender">
              <t-select v-model="formData.gender" placeholder="请选择性别">
                <t-option :value="GENDER_ENUM.MALE" :label="GENDER_MAP[GENDER_ENUM.MALE]"></t-option>
                <t-option :value="GENDER_ENUM.FEMALE" :label="GENDER_MAP[GENDER_ENUM.FEMALE]"></t-option>
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="年龄" name="age">
              <t-input v-model="formData.age" type="number" placeholder="请输入年龄" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="运动类别" name="activityType">
              <t-input v-model="formData.sportsCategory" placeholder="请输入技能，例如：网球" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="运动级别" name="sportsLevel">
              <t-select v-model="formData.sportsLevel" placeholder="请选择运动级别">
                <t-option
                  :value="SPORT_LEVEL_ENUM.BEGINNER"
                  :label="SPORT_LEVEL_MAP[SPORT_LEVEL_ENUM.BEGINNER]"
                ></t-option>
                <t-option
                  :value="SPORT_LEVEL_ENUM.INTERMEDIATE"
                  :label="SPORT_LEVEL_MAP[SPORT_LEVEL_ENUM.INTERMEDIATE]"
                ></t-option>
                <t-option
                  :value="SPORT_LEVEL_ENUM.ADVANCED"
                  :label="SPORT_LEVEL_MAP[SPORT_LEVEL_ENUM.ADVANCED]"
                ></t-option>
                <t-option
                  :value="SPORT_LEVEL_ENUM.PROFESSIONAL"
                  :label="SPORT_LEVEL_MAP[SPORT_LEVEL_ENUM.PROFESSIONAL]"
                ></t-option>
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="昵称" name="nickname">
              <t-input v-model="formData.nickname" placeholder="请输入昵称" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label-align="top" label="微信ID" name="wechatId">
              <t-input v-model="formData.wechatId" placeholder="请输入微信ID" />
            </t-form-item>
          </t-col>
        </t-row>
        <div class="form-basic-container-title form-title-gap">其他信息</div>
        <t-form-item label-align="top" label="备注" name="comment">
          <t-textarea v-model="formData.comment" :height="124" placeholder="请输入备注信息" />
        </t-form-item>
      </div>
    </div>

    <div class="form-submit-container">
      <div class="form-submit-sub">
        <div class="form-submit-left">
          <t-button theme="primary" class="form-submit-confirm" type="submit"> 保存</t-button>
          <t-button type="reset" class="form-submit-cancel" theme="default" variant="base"> 取消</t-button>
        </div>
      </div>
    </div>
  </t-form>
</template>

<style lang="less" scoped>
.form-basic-container {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--td-bg-color-container);
  border-radius: var(--td-radius-medium) var(--td-radius-medium) 0 0;
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl) 80px var(--td-comp-paddingLR-xxl);

  @media (max-width: @screen-sm-max) {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl) 80px var(--td-comp-paddingLR-xl);

    .form-basic-container-title {
      margin: 0 0 var(--td-comp-margin-xxxl) 0;
    }
  }

  .form-basic-item {
    width: 676px;

    .form-basic-container-title {
      font: var(--td-font-title-large);
      font-weight: 400;
      color: var(--td-text-color-primary);
      margin: var(--td-comp-margin-xxl) 0 var(--td-comp-margin-xl) 0;
    }

    .form-title-gap {
      margin: calc(var(--td-comp-margin-xxl) * 2) 0 var(--td-comp-margin-xl) 0;
    }
  }
}

.form-submit-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: var(--td-comp-paddingLR-xl);
  padding-bottom: var(--td-comp-paddingLR-xl);
  background-color: var(--td-bg-color-secondarycontainer);
  border-bottom-left-radius: var(--td-radius-medium);
  border-bottom-right-radius: var(--td-radius-medium);
  border-top: 1px solid var(--td-component-stroke);

  .form-submit-sub {
    width: 676px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .form-submit-left {
      .form-submit-upload-span {
        font-size: 14px;
        line-height: 22px;
        color: var(--td-text-color-placeholder);
        padding-top: 8px;
        display: inline-block;
      }
    }
  }
}
</style>
